<template>
  <view class="videoDetail" :class="{'tabbarHeiht': shareRouteData.shareType}">
    <cover-image
      v-if="!shareRouteData.shareType"
      class="goBack_box"
      :style="'top:'+globalData.menuButtonObject.top+'px;'"
      src="@/static/image/goBack_con.png"
      @click.stop="goBackFn">
     </cover-image>
     <cover-image
      v-else
      class="goBack_box"
      :style="'top:'+globalData.menuButtonObject.top+'px;'"
      src="@/static/image/goHome_con.png"
      @click.stop="goBackFn">
     </cover-image>
    <swiper
      class="video_swiper"
      vertical
      :skip-hidden-item-layout="true"
      @change="onSwiperChange"
      :current="swiperIndex"
    >
      <swiper-item v-for="(item, index) of videoList" :key="index">
        <view :style="'height: ' + (globalData.navTop - 10) + 'px;'"></view>
        <!-- 视频 -->
        <view
          v-if="item.mediaType === 2 && Math.abs(swiperIndex - index) <= 1"
          v-for="(video, idx) in item.dynamicMediaVOList"
          :key="idx"
          @click.stop="handClick(item)"
          class="videoBox"
          :class="{'filter24': isFilter}"
          :style="'height: calc(100% - ' + (globalData.navTop - 10) + 'px);'"
          @touchstart="onTouchstart"
          @touchend="onTouchend"
        >
          <video
            :id="`mp_video_${index}`"
            :ref="`mp_video_${index}`"
            class="video_file"
            :src="video.url"
            :poster="swiperIndex === index ? '' : video.url + '?x-oss-process=video/snapshot,t_100,f_jpg'"
            :object-fit="video.high > video.wide ? 'cover' : 'contain'"
            loop
            :controls="false"
            :enable-progress-gesture="false"
            :show-center-play-btn="false"
            @error="viodeError(index)"
          ></video>
          <image class="playIcon" src="https://image.qqpyyds.com/mpAppImg/icon/play3_icon.png" mode="widthFix"  v-if="clickStop && item.mediaType === 2" />
        </view>
        <!-- 图片 -->
        <view
          v-if="item.mediaType === 1 && Math.abs(swiperIndex - index) <= 1"
          class="videoBox"
          :class="{'filter24': isFilter}"
          :style="'height: calc(100% - ' + (globalData.navTop - 10) + 'px);'"
          @touchstart="onTouchstart"
          @touchend="onTouchend"
        >
          <swiper
            :autoplay="autoPlayImg"
            circular
            disable-touch
            @change="changeImage"
            :current="imageActiveIndex"
            style="width: 100; height: 100%; pointer-events: none;"

          >
            <swiper-item v-for="(img, idx) in item.dynamicMediaVOList" :key="idx">
              <!-- 背景图高斯模糊 -->
              <view class="swiper-bg" :style="'background-image:url('+img.url+');'"></view>
              <!-- 蒙层 -->
              <view class="swiper-bg_mantle"></view>
              <image :src="img.url" mode="widthFix" class="imgBox" />
            </swiper-item>
          </swiper>

        </view>
        <!-- 底部信息 -->
        <!-- v-if="videoList[swiperIndex].dynamicId === item.dynamicId" -->
        <!-- :goodsEndTiem="goodsEndTiem" -->
        <BottomMsg
        :ref="'bottomMsg'+item.dynamicId"
        :item="item"
        :imageActiveIndex="imageActiveIndex"
        :showTabbar="shareRouteData.shareType"
        @open="openBottom"
        @attention="attention"
        @clickLike="clickLike"
        @clickBestead="clickBestead"
        @openMore="moreShow = true"
        @openShare="openShare"
        @goHomePage="goHomePage"
        @toggleTitleShow="(val)=> isFilter = val"  />

        <!-- 手势引导滑动 用户首次进入视频流 && 第一条视频流 -->
        <view class="guideBox" v-if="isGuide && index === 0" @click="isGuide = false">
          <image src="https://qqposs.oss-cn-shenzhen.aliyuncs.com/mpAppImg/other/guideMap_img.png" style="width:336rpx;height:285rpx;" />
        </view>
      </swiper-item>
    </swiper>

    <!-- 商品列表弹窗 -->
    <!-- :goodsEndTiem="goodsEndTiem" -->
    <!-- :endTiem="videoList[swiperIndex].endTime" -->
    <GoodsMsgList
    :show="bottomShow"
    :goodsList="goodsList"
    :goodsCurrent="goodsCurrent"
    :item="videoList[swiperIndex]"
     @close="bottomShow = false" />

    <!-- 更多操作弹窗 -->
    <!-- :goodsEndTiem="goodsEndTiem" -->
    <!-- @dynamicStatus="dynamicStatus" -->
    <MorePopup
    :show="moreShow"
    :item="videoList[swiperIndex]"
    :routeData="routeData"
    @close="moreShow = false"
    @openShare="openShare"
    @clickBestead="clickBestead"
    @switchHide="switchHide"
    @removeDynamic="removeDynamic"
    @openUpEndTime="_updateEndTime"
    @isTop="isTop" />

    <!-- 一键帮卖弹窗 -->
    <u-popup v-model="oneSales" mode="bottom" border-radius="14">
      <view class="onePopup safe-bottom">
        <view class="headTitle tc fz-16 fw5">选择帮卖发布方式</view>
        <view class="px32 u-p-t-25 u-p-b-25" @click.stop="configBestead">
          <view class="fz-16">一键帮卖<text class="themeFontColor">（推荐）</text></view>
          <view class="viceColor u-p-t-8">直接复用内容一键帮卖</view>
        </view>
        <!-- <view class="px32 u-p-t-25 u-p-b-25" @click.stop="editBestead">
          <view class="fz-16">编辑后帮卖</view>
          <view class="viceColor u-p-t-8">可修改内容后再帮卖</view>
        </view> -->
        <view style="height:16rpx;background: #F7F8FA;"></view>
        <view class="tc fz-16 linh-50" style="color:#646566;" @click="oneSales = false">取消</view>
      </view>
    </u-popup>
    <!-- 发布动态开团成功弹窗 -->
    <PublishPopup v-if="isPublishPopup" :sharePublishData="sharePublishData"  @closeSharePublishFn="(flag)=>isPublishPopup=flag" />

    <!-- 视频缺省页 -->
    <view class="default" v-if="!videoList.length && routeData.currentPage > 1">
      没有视频了，快去关注更多达人
    </view>
    <!-- 底部tabbar -->
    <Tabbar theme="black" v-if="shareRouteData.shareType" />
    <!-- 申请帮卖关系 -->
    <ApplyForHelpSelling
      v-if="isHelpSellingShow"
      :show="isHelpSellingShow"
      :othersInfoData='othersInfoData'
      :routeData="routeData"
      :getRelationType="getRelationType"
      @cancelFn="cancelApplyForFn"
    />
    <!-- 分享好友模板弹窗 -->
    <SharePublicPage
      v-if="isSharePublicPage"
      :shareVideoData="shareVideoData"
      @cancelShareFn="cancelShareFn"
      @posterFn="posterFn"
    />
    <!-- 保存相册海报分享 -->
    <SharePoster
      v-if="posterShareShow"
      :shareVideoData="shareVideoData"
      @cancelSharePosterFn="cancelSharePosterFn"
    />
    <!-- 已经帮卖弹窗 -->
    <SoldForHelpSell v-if="isSoldForHelpSellShow" @closeSoldForFn="closeSoldForFn" @refreshOwnFn="refreshOwnFn" :soldForHelpSellId="soldForHelpSellId" />
  </view>
</template>
<script>
import Tabbar from "@/components/tabbar/index.vue";
import BottomMsg from "./bottomMsg.vue";
import GoodsMsgList from "./goodsMsgList.vue";
import MorePopup from "./morePopup.vue";
import dynamic from "@/api/dynamic.js";
import mini from "@/api/mini.js";
import supply from "@/api/supply.js";
import helpSellGroups from "@/api/helpSellGroups.js";
import mixin from "./videoDetail.js";
import Util from "@/api/util.js";
import PublishPopup from "@/components/publishPopup/index.vue";
import ApplyForHelpSelling from "../components/applyForHelpSelling.vue";
import SoldForHelpSell from '@/components/soldForHelpSell/index.vue'


// 分享好友模板
import SharePublicPage from "@/components/shareModal/sharePublicPage.vue"
// 分享海报
import SharePoster from "@/components/shareModal/sharePoster.vue"


export default {
  name: 'videoDetail',
  mixins: [mixin],
  components: {Tabbar, BottomMsg, GoodsMsgList, MorePopup, PublishPopup, SharePublicPage, SharePoster, ApplyForHelpSelling,SoldForHelpSell},
  computed: {
    globalData() {
      return this.$store.state.globalData;
    },
    // 是否通过分享进来，展示tabbar
    shareRouteData () {
      return this.$store.state.shareRouteData
    },
    // 分享进来邀请帮卖查询用户信息
    othersInfoData () {
      return this.$store.state.othersInfoData
    },
    // store中的关注后对象
    followTypeObj() {
      return this.$store.state.followTypeObj
    }
  },
  watch:{
    isLogin(nval,oval){
      if(nval !== oval && nval){ // 登录状态更新,从未登录到登录
        this.getData()
      }
    },
    followTypeObj(nVal) {
      if (nVal) {
        for (let i = 0, length = this.videoList.length; i < length; i++) {
          const item = this.videoList[i]
          if (item.accountId === nVal.accountId) {
            item.followStatus = nVal.followStatus
            // 此处不能清空--因为有两处需要用到--清空在另外一处监听不到
            // this.$store.commit('FOLLOW_TYPE', null)
          }
        }
      }
    }
  },
  data() {
    return {
      routeData: {}, // 请求参数

      videoList: [],
      swiperIndex: 0,
      lastTapDiffTime: 0,

      progress: 10000,
      progressValue: 0,
      clickStop: false, // 当前视频是否暂停

      imageActiveIndex: 0, // 图片swiper当前下标
      autoPlayImg: true, // 图片是否自动轮播

      bottomShow: false, // 弹窗状态,
      goodsList: [], // 商品列表
      goodsCurrent: 0,// 当前商品下标
      timer: null,
      // goodsEndTiem: '', // 团结束时间

      moreShow: false, // 操作弹窗
      oneSales: false, // 一键发布弹窗
      isPublishPopup: false, // 发布开团成功弹窗
      sharePublishData: {}, // 发布成功弹窗数据
      posterShareShow: false, // 海报相册保存弹窗
      posterShareData: {}, // 分享海报数据
      isHelpSellingShow: false, // 申请帮卖弹窗
      getRelationType: 0, // 帮卖关系
      drawWhiteShareCardData: {}, // 白色海报分享数据
      shareCanvasData: {}, // 海报分享绘图数据
      shareVideoData: {}, // 需要分享的视频对象
      isSharePublicPage: false, // 分享模板
      configBesteadDisable: false, //一键帮卖防止重复点击
      isSoldForHelpSellShow: false, // 帮卖过了不可帮卖
      soldForHelpSellId: '', // 已经帮卖返回自己帮卖团的id

      isFilter: false, // 是否高斯模糊
      isGuide: false, // 是否第一次进入视频流
    };
  },
  onReady() {
    // 自动播放
    let defaultVideo = uni.createVideoContext(`mp_video_0`, this); //进入页面开始播放第一个
    defaultVideo.play();
  },
  beforeDestroy(){
    if (this.timer) {
      clearInterval(this.timer)
      this.timer = null
    }
  },
  async onLoad(option) {
    wx.hideShareMenu({
      menus: ["shareAppMessage"]
    })
    uni.setNavigationBarColor({
      frontColor: "#ffffff",
      backgroundColor: "#ffffff",
      animation: {
        duration: 400,
        timingFunc: "easeIn",
      },
    });

    await this.isLoSignInFn(option) // 分享参数处理
    this.routeData = Object.assign({currentPage: 1, pageSize: 5, finish: false}, this.$store.state.shareRouteData)
    this.getData()


    // 获取红点规则
    if(this.isLogin){
      mini.getMyPageInfo().then(res=>{
        this.$store.commit('SET_MY_PAGEINFO',res.data)
      })
    }
  },
  onShow(){
    let updateData = this.$store.state.publicUpdateData
    if (updateData) { // 是否需要更新数据
      if (updateData.isFollow && this.videoList[updateData.index]) { // 处理页面去个人主页关注变动更新
        this.videoList[updateData.index].followStatus = updateData.isFollow
        this.$forceUpdate()
      }
      this.$store.commit('PUBLIC_UPDATE_DATA', null)
    }
  },
  onShareAppMessage(res) {
    const item = this.videoList[this.swiperIndex]
    const pageSharingData = this.$store.state.pageSharingData
    let title = ''
    let share_image = ''
    let path = `/pagesB/dynamic/videoDetail?dynamicId=${item.dynamicId}&shareType=true&type=2&idCode=${this.$store.state.userInfo.idCode}`
    if (res.from === 'button') {
      // 按钮分享
      if (res.target.id=="publishId") { // 发布成功分享参数
        title = this.sharePublishData.title
        share_image = this.sharePublishData.url
      }
      if (res.target.id=='sharewx') { // 公用分享
        if (pageSharingData.isShareType==2) {
          path = `/pagesB/dynamic/videoDetail?dynamicId=${item.dynamicId}&shareType=true&type=2&applyForHelp=true&idCode=${this.$store.state.userInfo.idCode}`
        }
        title = pageSharingData.title
        share_image = pageSharingData.url
      }
    }
    if (res.from === 'menu') {
      // 菜单分享
      // console.log(res.target)
    }

    // 分享参数打印
    console.log(JSON.parse(JSON.stringify({
      title: title,
      imageUrl: share_image,
      path: path
    })))

    return {
      title: title,
      imageUrl: share_image,
      path: path,
      success (res) {
      },
    }
  },
  //方法
  methods: {
    async getData(type){
      await this.getList() // 获取列表
      // if (this.videoList[this.swiperIndex].isGroup==2) this._beginTimer() // 团倒计时
      if(this.videoList.length > 1 && !(!!uni.getStorageSync('myVideoHide'))){
        this.isGuide = true
        uni.setStorageSync('myVideoHide',true)
      }

      this.videoList.length && dynamic.addBrowseLog({dynamicId: this.videoList[this.swiperIndex].dynamicId}) // 统计接口

      // 判断进入第一个动态是否为传入的动态 start
      if(this.videoList.length && this.routeData.dynamicId && this.videoList[0].dynamicId !== this.routeData.dynamicId){
        uni.showToast({
          title: type === 'delete' ? '已为你切换下一个视频' : '视频已经飞走了，已为你切换下一个视频',
          icon: 'none'
        })
      }
      if(type === 'delete'){
        this.$nextTick(()=>{
          let presentVideo = uni.createVideoContext(`mp_video_${this.swiperIndex}`,this); //当前视频
          presentVideo.pause(); //暂停播放
          setTimeout(() => {
            presentVideo.play(); // 继续播放
          }, 500);
        })
        return
      }
      // 判断进入第一个动态是否为传入的动态 end

      // 开团发布成功
      if (this.routeData.isReleasePopup && this.routeData.isReleasePopup>0 && this.videoList.length) this.releaseSuccessFn()
      // 邀请帮卖
      if ((this.routeData.dynamicId==this.videoList[this.swiperIndex].dynamicId)&&this.routeData.applyForHelp) this.getOthersInfoFn(this.videoList[this.swiperIndex].accountId)
    },
    // 获取动态列表
    async getList(){
      console.log(this.routeData,'请求参数');
      if(this.routeData.finish) return // 加载完毕，无更多数据
      let list = ""

      if(this.routeData.headAccountId){// 我的-分销管理-帮卖社群-帮卖的团
        const { data } = await helpSellGroups.getHelpSellDynamic(this.routeData)
        list = data.records
      }else if(this.routeData.groupAccountId){// 我的-分销管理-供货社群-可帮卖的团
        const { data } = await supply.getList(this.routeData)
        list = data.records
      }else if(this.routeData.type == 3 || this.routeData.accountId){// 为社群主页进入
        const { data } = await dynamic.getDynamicList(this.routeData)
        list = data.records
      }else if(this.routeData.type == 2 || this.routeData.shareType){//  为分享进入
        if(this.routeData.shareType){this.routeData.type = 2}
        const { data } = await dynamic.getDynamicList(this.routeData)
        list = data.records
      }else{// 调取首页视频流接口
        const { data } = await mini.getHomeDynamics(this.routeData)
        list = data.records
      }
    
      this.videoList = [...this.videoList,...list]
      if(this.routeData.pageSize === 1){ // 只加载一个动态
        this.routeData.finish = true
        return
      }
      this.routeData.finish = ((this.routeData.currentPage * this.routeData.pageSize) !== this.videoList.length)
      this.routeData.currentPage++ // 再次调取，直接加载下一页
    },
    // 视频列表切换
    onSwiperChange(e) {
      this.isGuide = false
      this.imageActiveIndex = 0
      // 在下标赋值之前,把上个播放的视频暂停
      let nextVideo = uni.createVideoContext(
        `mp_video_${this.swiperIndex}`,
        this
      ); //下一个视频
      nextVideo.pause(); //暂停播放
      this.swiperIndex = e.detail.current; // 当前播放下标
      // 自动播放
      this.clickStop = false;
      let presentVideo = uni.createVideoContext(
        `mp_video_${this.swiperIndex}`,
        this
      ); //当前视频
      presentVideo.play();

      this.videoList.length && dynamic.addBrowseLog({dynamicId: this.videoList[this.swiperIndex].dynamicId}) // 统计接口
      if (this.swiperIndex === this.videoList.length - 2 && !this.routeData.finish) {
        // 滑动到倒数第二个视频时-以及数据未加载完毕
        console.log("加载更多");
        this.getList()
      }
    },
    // 图片轮播切换
    changeImage(e) {
      this.imageActiveIndex = e.detail.current;
    },
    // 单击或双击
    handClick(item) {
      let _this = this;
      let curTime = new Date().getTime();
      let lastTime = _this.lastTapDiffTime;
      _this.lastTapDiffTime = curTime;
      //两次点击间隔小于300ms, 认为是双击
      let diff = curTime - lastTime;
      if (diff < 300) {
        console.log("双击点赞");
        if(!item.isLike){
          let params = {
            type: 1,
            sourceId: item.dynamicId,
            isLike: 1 // 1点赞
          }
          dynamic.giveLike(params).then(res=>{
            this.videoList[this.swiperIndex].isLike = params.isLike // 改变状态
            params.isLike ? this.videoList[this.swiperIndex].likeCount++ : this.videoList[this.swiperIndex].likeCount-- // 改变点赞数
          })
        }
        clearTimeout(_this.lastTapTimeoutFunc); // 成功触发双击事件时，取消单击事件的执行
      } else {
        // 单击事件延时300毫秒执行
        _this.lastTapTimeoutFunc = setTimeout(function () {
          console.log("单击暂停");
          let presentVideo = uni.createVideoContext(
            `mp_video_${_this.swiperIndex}`,
            _this
          ); //当前视频
          if (_this.clickStop) {
            //已暂停
            presentVideo.play();
            _this.clickStop = false;
          } else {
            // 播放中
            presentVideo.pause(); //暂停播放
            _this.clickStop = true;
          }
        }, 300);
      }
    },
    // 触摸开始，多点触控，后面的手指同样会触发
    onTouchstart(e) {
      this.progress = e.changedTouches[0].clientX; // 开始X坐标
      this.autoPlayImg = false
    },
    // 手指触摸动作结束
    onTouchend(e) {
      const clientX = e.changedTouches[0].clientX; // 结束X坐标
      if (this.progress - clientX > 100) {
        // 图片切换下一张
        if(this.videoList[this.swiperIndex].mediaType === 1){
          const imgLength = this.videoList[this.swiperIndex].dynamicMediaVOList.length - 1
          this.imageActiveIndex >= imgLength ? this.imageActiveIndex = 0 : this.imageActiveIndex++
        }else{// 视频进入作者主页
          this.goHomePage()
        }
        this.autoPlayImg = true
      }
      // this.progressValue = parseInt((e.changedTouches[0].clientX / this.screenWidth) * 100);
    },
    // 视频播放出错
    viodeError(index){
      this.videoList[index].dynamicMediaVOList[0].url += `?t=${Date.parse(new Date())}`
      let presentVideo = uni.createVideoContext(`mp_video_${this.swiperIndex}`,this); //当前视频
      presentVideo.play();
    }
    // 团倒计时
    // _beginTimer(){
    //   this.timer = setInterval(() => {
    //     if(this.videoList.length){
    //       const item = this.videoList[this.swiperIndex]
    //       const data = Util.countdownPay(Date.parse(new Date(item.endTime.replace(/-/g, "/")))) // 截止时间
    //       if (!data || data.code==201) { // 团结束
    //         this.goodsEndTiem = ''
    //         clearInterval(this.timer)
    //       }else{
    //         if (data.day>0) {
    //           this.goodsEndTiem = `${data.day}天  ${data.hr}:${data.min}:${data.sec}`
    //         }else{
    //           this.goodsEndTiem = `${data.hr}:${data.min}:${data.sec}`
    //         }
    //       }
    //     }
    //   }, 1000);
    // },
    // // 手指触摸后移动，滑动
    // onTouchmove(e) {
    //   //手指当前坐标
    //   const clientX = e.changedTouches[0].clientX;
    //   this.progress = parseInt((clientX / this.screenWidth) * 100);
    //   console.log(this.progress,'触摸移动');
    // },
    // // 手指触摸动作被打断，如来电提醒，弹窗
    // onTouchcancel(e) {
    //   this.progressValue = parseInt(
    //     (e.changedTouches[0].clientX / this.screenWidth) * 100
    //   );
    //   console.log(this.progressValue,'触摸打断');
    // },
  },
};
</script>
<style lang="scss">
// 不存在tabbar
.videoDetail {
  width: 100%;
  height: 100vh;
  overflow: hidden;
  position: relative;
  background: #000;
  .filter24{
    filter: blur(24px);
  } 
  .goBack_box {
    position: fixed;
    z-index: 999;
    width: 60rpx;
    height: 60rpx;
    left: 32rpx;
    top: 48px;
  }
  .video_swiper {
    width: 100%;
    height: 100%;
  }
  .videoBox {
    width: 100%;
    position: relative;
    overflow: hidden;
    .video_file {
      width: 100%;
      height: 100%;
      border-radius: 20rpx 20rpx 0 0;
    }
    .playIcon {
      width: 100rpx;
      height: auto;
      color: #ffffff;
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      z-index: 997;
    }
    .swiper-bg {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      z-index: 0;
      filter: blur(24px);
      background-size: contain;
    }
    .swiper-bg_mantle {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      z-index: 1;
      background: rgba(0, 0, 0, 0.5);
    }
    .imgBox {
      width: 100%;
      height: auto;
      position: absolute;
      top: 50%;
      left: 0;
      transform: translateY(-50%);
      z-index: 9;
    }
  }
  .onePopup{
    .headTitle {
      line-height: 96rpx;
      box-shadow: inset 0px -1px 0px #eeeeee;
    }
  }
  .default{
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: #323233;
    color: #F7F8FA;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

// 存在tabbar
.videoDetail.tabbarHeiht{
  height: calc(100vh - 100rpx);
  height: calc(100vh - 100rpx - constant(safe-area-inset-bottom));
  height: calc(100vh - 100rpx - env(safe-area-inset-bottom));
}

.guideBox{
  display: flex;
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.5);
  align-items: center;
  justify-content: center;
}
</style>